import router from '@/router'
import store from '@/store'
import { NO_LOGIN_PATH } from '@/config'
import { getToken, getRoles } from '@/utils/user'
import { isShowLogin } from '@/utils/request'
import { msgError } from '@/plugins/modal'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false })
router.beforeEach(async (to, from, next) => {
  NProgress.start()

  const initConfig = store.getters.config || null
  if (!initConfig) {
    try {
      await store.dispatch('app/initConfig')
    } catch (e) {
      if (to.name !== 'InitFail'){
        return next({name: 'InitFail'})
      } else {
        return next()
      }
    }
  }
  if (to.name === 'InitFail'){
    return next({ name: 'Index', replace: true })
  }
  if (getToken()) {
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    if (to.name === 'Login') {
      return next({ name: 'Index' })
    }
    if (NO_LOGIN_PATH.indexOf(to.path) !== -1) {
      return next()
    }
    if (getRoles().length === 0) {
      isShowLogin.show = true
      // 判断当前用户是否已拉取完user_info信息
      store
        .dispatch('user/AuthInfo')
        .then(() => {
          isShowLogin.show = false
          store.dispatch('GenerateRoutes').then(accessRoutes => {
            // 根据roles权限生成可访问的路由表
            router.addRoutes(accessRoutes) // 动态添加可访问路由表
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          })
        })

        .catch(err => {
          store.dispatch('user/LogOut').then(() => {
            msgError(err)
            next({ name: 'Index' })
          })
        })
    } else {
      next()
    }
  } else {
    if (NO_LOGIN_PATH.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      // 否则全部重定向到登录页
      next({name:'Login', query: {redirect: to.fullPath}, replace: true})
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
